package kr.hkit.android_bookmgr.activity;

import java.util.ArrayList;

import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;

import kr.hkit.android_bookmgr.R;
import kr.hkit.android_bookmgr.DAO.BookDAO;
import kr.hkit.android_bookmgr.DTO.BookData;
import kr.hkit.android_bookmgr.DTO.MemoData;
import kr.hkit.android_bookmgr.adapter.MemoBaseAdapter;
import kr.hkit.android_bookmgr.util.ImageUtil;
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemLongClickListener;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class BookMemoActivity extends Activity {
	
	private BookDAO mBookMgr;
	private ListView memoList;
	private ArrayList<MemoData> memoItems;
	private MemoBaseAdapter adapter;
	private int longPos;
	private BookData book;
	
	//메모화면
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bookmemo_activity);
		
		ActionBar mActionBar = getActionBar();
		mActionBar.setDisplayHomeAsUpEnabled(true); 
		mActionBar.setHomeButtonEnabled(true);

		mBookMgr = BookDAO.getInstance(this);
		
		Bundle bundle = this.getIntent().getExtras();
		book = bundle.getParcelable("BOOK");
		Log.d("BOOK1", book.getAuthor() + " bookmarkedit");
		
		TextView name = (TextView) findViewById(R.id.bookmemo_name);
		name.setText(book.getName());
		TextView author = (TextView) findViewById(R.id.bookmemo_author);
		author.setText(book.getAuthor());
		TextView startdate = (TextView) findViewById(R.id.bookmemo_startdate);
		startdate.setText(book.getStartdate());
		TextView enddate = (TextView) findViewById(R.id.bookmemo_enddate);
		enddate.setText(book.getEnddate());
		
		ImageView img = (ImageView) findViewById(R.id.bookmemo_img);
		ImageUtil.imageLoader(BookMemoActivity.this);
		DisplayImageOptions options = ImageUtil.dispalyOptions();
		if (book.getImgtype()==0){ //직찍
			ImageLoader.getInstance().displayImage("file:///"+book.getBookimg(), img, options);
		}else if(book.getImgtype()==1){ //갤러리
			ImageLoader.getInstance().displayImage("content://media/"+book.getBookimg(), img, options);
		}else{ //검색
			ImageLoader.getInstance().displayImage(book.getBookimg(), img, options);
		}

		
		
		//메모 리스팅
		memoList = (ListView) findViewById(R.id.bookmemo_listview);
		memoItems = mBookMgr.selectListMemoByBookId(book.getId());
		adapter = new MemoBaseAdapter(BookMemoActivity.this, memoItems);
		memoList.setAdapter(adapter);
		
		int memoCount = adapter.getCount();
		LinearLayout linearMemo = (LinearLayout) findViewById(R.id.bookmemo_centerlinear);
		if (memoCount!=0){
			linearMemo.setVisibility(LinearLayout.GONE);
		}
		
		
		
		//메모 수정, 삭제 - 롱클릭 
		memoList.setOnItemLongClickListener(new OnItemLongClickListener() {

			@Override
			public boolean onItemLongClick(AdapterView<?> parent, View view,
					int position, long id) {

				longPos = position;
				
				new AlertDialog.Builder(BookMemoActivity.this).
				setTitle("원하는 항목을 선택하십시오.").
				setItems(R.array.booklist_updel, new DialogInterface.OnClickListener() {
					@Override
					public void onClick(DialogInterface dialog, int which) {
						
						//String[] pickimg = getResources().getStringArray(R.array.booklist_updel);
						
						if(which==0){ //수정
							
							Bundle extra = new Bundle();
							extra.putInt("memoId", memoItems.get(longPos).memoId);
							extra.putString("writedate", memoItems.get(longPos).writedate);
							extra.putString("review", memoItems.get(longPos).review);
							extra.putInt("wordspage", memoItems.get(longPos).wordspage);
							extra.putString("words", memoItems.get(longPos).words);
							extra.putString("memoimg", memoItems.get(longPos).memoimg);
							extra.putInt("memoimgtype", memoItems.get(longPos).memoimgtype);
							
							Intent intent = new Intent(BookMemoActivity.this, BookMemoEditActivity.class);
							intent.putExtras(extra);
							startActivity(intent);
							
							//Toast.makeText(getBaseContext(), memoItems.get(longPos).memoId+"", Toast.LENGTH_SHORT).show();					
						
						}else if (which==1){ // 삭제 확인창 띄우기 
							new AlertDialog.Builder(BookMemoActivity.this)
							.setTitle("메모 삭제")
							.setMessage("해당 메모를 삭제하시겠습니까?")
							.setPositiveButton("확인", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) { //등록버튼 클릭시 -> DB인서트
									String whereClause = "_id=?";
									String[] whereArgs = new String[1];
									whereArgs[0]=Integer.toString(memoItems.get(longPos).memoId);
									mBookMgr.deleteMemo(whereClause, whereArgs);
									
									//Toast.makeText(getBaseContext(), "메모ID: "+ memoItems.get(longPos).memoId+ "삭제 되었습니다.", Toast.LENGTH_SHORT).show();
								
									//삭제 후 메모리스트 재호출
									memoItems = mBookMgr.selectListMemoByBookId(book.getId());
									adapter = new MemoBaseAdapter(BookMemoActivity.this, memoItems);
									memoList.setAdapter(adapter);
									
								}
							})
							.setNegativeButton("취소", new DialogInterface.OnClickListener() {
								public void onClick(DialogInterface dialog, int whichButton) {
									Toast.makeText(getBaseContext(),"취소하였습니다.", Toast.LENGTH_SHORT).show();
								}
							})
							.show();
							//삭제확인 AlertDialog
							
						}/*else{ //공유.... 텍스트만 됨
							Intent intent = new Intent(Intent.ACTION_SEND);
							intent.setType("text/plain");
							intent.putExtra(Intent.EXTRA_TEXT, memoItems.get(longPos).words); //word보내기 
							BookMemoActivity.this.startActivity(intent);
						
						}//if~else
*/						
					}//onClick 수정, 삭제 대화상자
				})
				.setNegativeButton("취소", null)
				.show();
				return true;
			}
		});
	}//onCreate
	

	 private String getPath(Uri uri) {  
	        String[] projection = { MediaStore.Images.Media.DATA };  
	  
	        Cursor cursor = managedQuery(uri, projection, null, null, null);  
	        int column_index = cursor  
	        .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);  
	        cursor.moveToFirst();  
	  
	        return cursor.getString(column_index);  
	    }  
	
	
	@Override
	protected void onRestart() {
		super.onRestart();
		memoList = (ListView) findViewById(R.id.bookmemo_listview);
		memoItems = mBookMgr.selectListMemoByBookId(book.getId());
		adapter= new MemoBaseAdapter(BookMemoActivity.this, memoItems);
		memoList.setAdapter(adapter);
		
		int memoCount = adapter.getCount();
		LinearLayout linearMemo = (LinearLayout) findViewById(R.id.bookmemo_centerlinear);
		if (memoCount!=0){
			linearMemo.setVisibility(LinearLayout.GONE);
		}
		
	}
	
	
	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.menu.bookmemo_actionbarmenu, menu);
		return super.onCreateOptionsMenu(menu);
	}//onCreateOptionsMenu
	
	
	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		switch(item.getItemId()){
		case R.id.bookmemo_icon: // 메모등록페이지로
			Intent intent = new Intent(BookMemoActivity.this,BookMemoAddActivity.class);
			intent.putExtra("id", book.getId());
			startActivity(intent);
			break;
		case android.R.id.home:
			intent = new Intent(this, BookListActivity.class);
			intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); // 액티비티 쌓이지 않기위해.
			startActivity(intent);
			break;
		}
		return super.onOptionsItemSelected(item);
	}//onOptionsItemSelected

}//end of class
